# coding=utf-8
import time
from threading import Thread
import traceback
import requests
from flask import Flask, request, json,make_response
from gevent import pywsgi
import logging

# 实例化Flask类
app = Flask(__name__)


json_response = {"description":".........BMS.........BMS.....................","result":"0"}
json_response_fail = {"description":".........BMS.........BMS.....................","result":"-1"}
json_resultnotify= {"correlateid":"1935173","mediaID":"10280102","mediaCode":"regist10280102","result":"0","description":"处理成功"}

def doPost(url, data=None):
    headers = {"content-type": "application/json"}
    time.sleep(3)
    print(url,data)
    try:
        response = requests.post(url=url, headers=headers, data=data, verify=False,timeout=3)
        print(response)
        if response.status_code != 200:
            print (" Fail")
            return -1
        else:
            print ("%s: ResultNotify Success" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            return 0
    except Exception :
        print (" send json request Fail,check DestUrl")
        traceback.print_exc()
        return -1

url = "https://172.19.64.71:8082/scms-output-dispatcher/notify/callback"

logging.basicConfig(filename='callback_httpjson_chance.log', level=logging.INFO,
                    format='%(asctime)s %(levelname)s %(message)s')
@app.route("/json/services/ctms", methods=['POST'])
def postsoap():
    reqdata = request.get_json()
    print(reqdata)
    app.logger.info('Received request: %s %s', request.path, reqdata)
    # 将请求信息写入日志文件
    logging.info('Received request: %s %s', request.path, reqdata)

    if reqdata is not None:
        Correlateid = reqdata.get('Correlateid')
        MediaID = reqdata.get('MediaID')
        MediaCode = reqdata.get('MediaCode')
    json_resultnotify["correlateid"] = Correlateid
    json_resultnotify["mediaID"] = MediaID
    json_resultnotify["mediaCode"] = MediaCode
    data = json.dumps(json_resultnotify)
    print(type(json_resultnotify))
    # data = data.encode('utf-8')
    print(json_resultnotify)
    thread = Thread(target=doPost,kwargs={'url':url,'data':data})
    logging.info('ResultNotify: %s %s', url, data)
    thread.start()
    rsp = make_response(json_response)
    rsp.headers['Content-Type'] = 'application/json'
    print(rsp)
    return rsp

if __name__ == '__main__':
    #app.run(host='172.19.132.137:6666',debug=True)
    server= pywsgi.WSGIServer(('172.19.97.208', 8888), app)
    server.serve_forever()
